package token

import (
	"bytes"
	"encoding/hex"
	"strconv"
)

type AttributeValue []byte

func (t AttributeValue) String() string {
	return string(t)
}

func (t AttributeValue) FromUint() uint64 {
	ret, _ := strconv.ParseUint(string(t), 10, 64)
	return ret
}

var hexPrefix = []byte("0x")

func (t AttributeValue) FromHex() []byte {
	if len(t) < 2 || !bytes.EqualFold(t[:2], hexPrefix) {
		return nil
	}
	dst := make([]byte, hex.DecodedLen(len(t)))
	n, err := hex.Decode(dst, t[2:])
	if err != nil {
		return nil
	}
	return dst[:n]
}

func (t AttributeValue) FromFloat() float64 {
	ret, _ := strconv.ParseFloat(string(t), 10)
	return ret
}

func (t AttributeValue) FromString() string {
	if len(t) < 2 || t[0] != '"' || t[len(t)-1] != '"' {
		return ""
	}
	// 根据RFC8216, 以下字符不得出现在 quoted-string 中：换行 (0xA)、回车 (0xD) 或双引号 (0x22).
	// 这意味着无需处理这类转义.
	return string(t[1 : len(t)-1])
}

var resolutionSpilt = []byte("x")

func (t AttributeValue) FromResolution() (x, y uint64) {
	x_, y_, ok := bytes.Cut(t, resolutionSpilt)
	if !ok {
		return 0, 0
	}
	x, _ = strconv.ParseUint(string(x_), 10, 64)
	y, _ = strconv.ParseUint(string(y_), 10, 64)
	return
}

type Attributes map[string]AttributeValue
